package com.gitee.lougnib.simple.lang.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LSystemUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(LPropertiesUtils.class);

	/**
	 * 获取本系统的 IP 地址。
	 *
	 * @return 字符串形式的 IP 地址
	 */
	public static String getLocalIp() {
		String ip = StringUtils.EMPTY;
		InetAddress inet = getSystemInetAddress();
		if (null != inet) {
			ip = inet.getHostAddress();
		}

		return ip;
	}

	private static InetAddress getSystemInetAddress() {
		InetAddress inet = null;

		try {
			String osName = System.getProperties().getProperty("os.name");
			if ("Windows".compareToIgnoreCase(osName) < 0) {
				inet = InetAddress.getLocalHost();
			} else {
				inet = getUnixInetAddress();
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
		return inet;
	}

	private static InetAddress getUnixInetAddress() throws Exception {
		Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
		if (null == netInterfaces) {
			throw new Exception("获取类 Unix 系统的 IP 失败");
		}

		while (netInterfaces.hasMoreElements()) {
			NetworkInterface ni = netInterfaces.nextElement();
			if (ni.isUp()) {
				Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
				while (inetAddresses.hasMoreElements()) {
					InetAddress ip = inetAddresses.nextElement();
					if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
						return ip;
					}
				}
			}
		}

		throw new Exception("获取类 Unix 系统的 IP 失败");
	}
}
